package com.ruibang.glass.quality.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.ruibang.glass.quality.constant.Constants;
import com.ruibang.glass.quality.domain.req.InspectionDefectStatisticsReq;
import com.ruibang.glass.quality.domain.resp.InspectionDefectStatisticsResp;
import com.ruibang.glass.quality.entity.InspectionDefectStatisticsRule;
import com.ruibang.glass.quality.mapper.TotalEquDataMapper;
import com.ruibang.glass.quality.service.InspectionDefectStatisticsRuleService;
import com.ruibang.glass.quality.service.InspectionDefectStatisticsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: songJinKang
 * @CreateTime: 2024-02-23  15:12
 * @Description: TODO
 * @Version: 1.0
 */
@Slf4j
@Service
public class InspectionDefectStatisticsServiceImpl implements InspectionDefectStatisticsService {

    @Autowired
    private TotalEquDataMapper totalEquDataMapper;
    @Autowired
    private InspectionDefectStatisticsRuleService inspectionDefectStatisticsRuleService;

    @Override
    public Object query(InspectionDefectStatisticsReq inspectionDefectStatisticsReq) {
        if (StringUtils.isBlank(inspectionDefectStatisticsReq.getGlassId()) && inspectionDefectStatisticsReq.getStartTime() == null
                && inspectionDefectStatisticsReq.getEndTime() == null) {
            inspectionDefectStatisticsReq.setStartTime(LocalDateTime.now().minusHours(3));
            inspectionDefectStatisticsReq.setEndTime(LocalDateTime.now());
        }
        List<InspectionDefectStatisticsResp> inspectionDefectData = totalEquDataMapper.queryInspectionDefectData(inspectionDefectStatisticsReq);
        if (CollectionUtils.isNotEmpty(inspectionDefectData)) {
            Map<String, Object> dataMap = new LinkedHashMap<>();
            //获取规则
            List<InspectionDefectStatisticsRule> ruleList = inspectionDefectStatisticsRuleService.list();
            if (CollectionUtils.isNotEmpty(ruleList)) {
                Map<String, List<InspectionDefectStatisticsRule>> ruleMap = ruleList.stream().collect(Collectors.groupingBy(InspectionDefectStatisticsRule::getRuleType));
                //预制统计数据
                Map<String, Integer> countMap = new LinkedHashMap<>();
                List<String> keySet = new ArrayList<>(ruleMap.keySet());
                customSort(keySet);
                for (String key : keySet) {
                    countMap.put(key.concat("未复检"), 0);
                    countMap.put(key.concat("已复检"), 0);
                }
                for (InspectionDefectStatisticsResp data : inspectionDefectData) {
                    List<String> ruleName = new ArrayList<>();
                    ruleMap.forEach((k, j) -> {
                        //获取X规则数据
                        InspectionDefectStatisticsRule xRule = null;
                        for (InspectionDefectStatisticsRule inspectionDefectStatisticsRule : j) {
                            if (inspectionDefectStatisticsRule.getCoordinate().equals(Constants.COORDINATE_X)) {
                                xRule = inspectionDefectStatisticsRule;
                                break;
                            }
                        }
                        j = j.stream().filter(e -> Constants.COORDINATE_Y.equals(e.getCoordinate())).collect(Collectors.toList());
                        if (xRule != null) {
                            for (InspectionDefectStatisticsRule yRule : j) {
                                boolean bool = processRule(data, xRule, yRule);
                                if (bool) {
                                    //添加规则名称
                                    ruleName.add(k);
                                    //统计个数
                                    if (data.getTiltedDiv() == Constants.ZERO_INT) {
                                        String key = k.concat("未复检");
                                        Integer count = countMap.get(key);
                                        if (count != null) {
                                            countMap.put(key, count + 1);
                                        }
                                    } else {
                                        String key = k.concat("已复检");
                                        Integer count = countMap.get(key);
                                        if (count != null) {
                                            countMap.put(key, count + 1);
                                        }
                                    }
                                    break;
                                }
                            }
                        } else {
                            throw new RuntimeException("X坐标规则未配置，请重新配置规则");
                        }
                    });
                    data.setRuleName(ruleName.stream().distinct().collect(Collectors.toList()));
                }
                dataMap.putAll(countMap);
            }
            dataMap.put("inspectionDefectData", inspectionDefectData);
            return dataMap;
        }
        return Collections.emptyList();
    }


    private boolean processRule(InspectionDefectStatisticsResp data, InspectionDefectStatisticsRule xRule, InspectionDefectStatisticsRule yRule) {
        return (ruleJudgment(xRule.getComparisonOperatorOne(), xRule.getThresholdValueOne(), data.getMaterialCenterDW()) && ruleJudgment(xRule.getComparisonOperatorTwo(), xRule.getThresholdValueTwo(), data.getMaterialCenterDW()))
                && ruleJudgment(yRule.getComparisonOperatorOne(), yRule.getThresholdValueOne(), data.getMaterialCenterCW()) && ruleJudgment(yRule.getComparisonOperatorTwo(), yRule.getThresholdValueTwo(), data.getMaterialCenterCW());
    }


    private boolean ruleJudgment(String comparisonOperator, double thresholdValue, double coordinateData) {
        switch (comparisonOperator) {
            case ">": {
                return coordinateData > thresholdValue;
            }
            case "<": {
                return coordinateData < thresholdValue;
            }
            case ">=": {
                return coordinateData >= thresholdValue;
            }
            case "<=": {
                return coordinateData <= thresholdValue;
            }
            default: {
                return false;
            }
        }
    }

    public static void customSort(List<String> list) {
        Collections.sort(list, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                int index1 = getIndex(o1);
                int index2 = getIndex(o2);
                if (index1 != index2) {
                    return index1 - index2;
                } else {
                    return extractNumber(o1) - extractNumber(o2);
                }
            }

            private int getIndex(String s) {
                if ("RT2.1".equals(s)) {
                    return 0;
                } else if ("RT2.2".equals(s)) {
                    return 1;
                } else if ("RT1左边".equals(s)) {
                    return 2;
                } else {
                    return 3;
                }
            }

            private int extractNumber(String s) {
                String[] parts = s.split("\\.");
                if (parts.length > 1) {
                    try {
                        return Integer.parseInt(parts[1]);
                    } catch (NumberFormatException e) {
                        log.error("排序异常 customSort ：{}", e.getMessage());
                    }
                }
                return 0;
            }
        });
    }

}
